package com.overlook.somniferous.common.util;

import com.overlook.somniferous.common.po.PageParamDto;
import com.overlook.somniferous.common.po.PageResult;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 自定义分页工具类
 */
@Component
public class PageUtil {

    public static <T> PageResult<T> page(List<T> list, PageParamDto pageParam) {
        PageResult<T> pageResult = new PageResult<>();
        if (CollectionUtils.isEmpty(list)) {
            return pageResult;
        }
        pageResult.setPageSize(pageParam.getPageSize());
        pageResult.setPageNum(pageParam.getPageNum());
        pageResult.setTotalSize(list.size());
        int remainder = list.size() % pageParam.getPageSize();
        int totalPage = remainder == 0 ? list.size() / pageResult.getPageSize() : list.size() / pageResult.getPageSize() + 1;
        //页码超过最大页数时
        if (pageParam.getPageNum() >= totalPage) {
            pageParam.setPageNum(totalPage);
        }
        pageResult.setTotalPage(totalPage);
        //数据量小于页面容量时
        if (list.size() <= pageParam.getPageSize()) {
            pageResult.setList(list);
        } else {
            int pageNumIndex = pageParam.getPageNum() - 1;
            int toIndex = Math.min(pageParam.getPageNum() * pageParam.getPageSize(), list.size());
            List<T> subList = list.subList(pageNumIndex * pageParam.getPageSize(), toIndex);
            pageResult.setList(subList);
        }
        return pageResult;
    }

}
